package net.zjitc.utils.dispacher;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import net.zjitc.controller.ProductController;
import net.zjitc.utils.ControllerUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/8.
 */
//在此DispacherServlet里面去分配或高度到底是哪个类的什么方法
@WebServlet(name = "DispacherServlet",urlPatterns = "/")
public class DispacherServlet extends HttpServlet {
    Map<String,Method> urlMap = new HashMap<>();
    Map<Method,Object> methodMap = new HashMap<>();
    @Override
    public void init() throws ServletException {
       // 1.遍历net.zjitc.controller包下面的所有的Class对象，
        String packName = "net.zjitc.controller";
        try {
            List<Class> classes = ControllerUtils.getAllClass(packName);
            // 2. 找到类对象的所有的方法 ，
            for(Class c: classes){
                Method[] methods = c.getMethods();
                for(Method m:methods){
                   // 3.判断方法上面是否有注解，如果有注解，才把它们放在map集合中，
                    URLMapping annotation = m.getAnnotation(URLMapping.class);
                    if (annotation!=null){
                        String url = annotation.url();
                        urlMap.put(url,m);
                        Object o = c.newInstance();
                        methodMap.put(m,o);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /**      1.遍历net.zjitc.controller包下面的所有的.class文件，
     *      2. 找到类对象的所有的方法 ，
     *      3.判断方法上面是否有注解，如果有注解，才把它们放在map集合中，
     */

    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

         String url =  req.getServletPath();
        /**
         * net.zjitc.controller  ----.java
         *
         * urlMap<url,method>
         *  methodMap  <method,object >
         *      method.invoke(object,request,response)
         *  */

        Method m = urlMap.get(url);
        Object o = methodMap.get(m);
        try {
           String str = (String) m.invoke(o,req,resp);
           if (str!=null || (!"".equals(str))){
               if (str.startsWith("Redirect:")){
                   resp.sendRedirect(str.substring(9));
               }else {
                   req.getRequestDispatcher(str).forward(req,resp);
               }
           }

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }




}
